/**
 * 语音朗读模块
 */
import request from './request.js';

class SpeechModule {
    constructor(options = {}) {
        this.options = {
            autoPlay: false, // 是否自动播放
            onStart: null,   // 开始播放回调
            onEnd: null,     // 结束播放回调
            onError: null,   // 错误回调
            ...options
        };
        this.innerAudioContext = null;
    }

    /**
     * 初始化语音上下文
     */
    init() {
        if (this.innerAudioContext) {
            this.innerAudioContext.destroy();
        }
        
        this.innerAudioContext = uni.createInnerAudioContext();
        
        // 设置事件监听
        this.innerAudioContext.onPlay(() => {
            this.options.onStart && this.options.onStart();
        });
        
        this.innerAudioContext.onEnded(() => {
            this.options.onEnd && this.options.onEnd();
        });
        
        this.innerAudioContext.onError((res) => {
            this.options.onError && this.options.onError(res);
        });
    }

    /**
     * 播放文本
     * @param {string} text 要播放的文本
     */
    play(text) {
        if (!this.innerAudioContext) {
            this.init();
        }
        
        this.innerAudioContext.src = `${request.SERVER_URL}/speack?text=${encodeURIComponent(text)}`;
        
        if (this.options.autoPlay) {
            this.innerAudioContext.play();
        }
    }

    /**
     * 停止播放
     */
    stop() {
        if (this.innerAudioContext) {
            this.innerAudioContext.stop();
        }
    }

    /**
     * 销毁实例
     */
    destroy() {
        if (this.innerAudioContext) {
            this.innerAudioContext.destroy();
            this.innerAudioContext = null;
        }
    }
}

export default SpeechModule; 